#include <stdio.h>
#include <locale.h>
#include <sys/types.h>	       /* See NOTES */
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/can.h>
#include <net/if.h>
#include <string.h>
#include <unistd.h>

#define CAN_MTU (sizeof(struct can_frame))
#define CAN_DEVICE "vcan1" 

int main(int argc, const char *argv[])
{
	int can_sockfd;
	struct sockaddr_can can_addr;
	struct ifreq ifr;

	setlocale(LC_ALL, "");

	can_sockfd = socket(AF_CAN, SOCK_RAW, CAN_RAW);

	strcpy(ifr.ifr_name, CAN_DEVICE);
	ioctl(can_sockfd, SIOCGIFINDEX, &ifr);

	memset(&can_addr, 0, sizeof(can_addr));
	can_addr.can_family = AF_CAN;
	can_addr.can_ifindex = ifr.ifr_ifindex;

	bind(can_sockfd, (struct sockaddr *)&can_addr, sizeof(can_addr));

	struct can_frame frame;
	int ret = -1;
	int i=-1;
	while(1) {
		ret = read(can_sockfd, &frame, CAN_MTU);
		if (ret < 0) {
			perror("can raw socket read");
			return -1;
		}
		if (ret < CAN_MTU) {
			fprintf(stderr, "read: incomplete CAN frame\n");
			return -1;
		}
		printf("can_id:%08x\n",frame.can_id);
		printf("data:");
		for (i = 0; i < frame.can_dlc; ++i) {
			printf("%02x ", frame.data[i]);
		}
		printf("\n");
		
	}

	return 0;
}
